package org.smart4j.framework.bean;


import org.apache.commons.collections4.CollectionUtils;
import org.smart4j.framework.util.StringUtil;

import java.util.*;

/**
 * 封装 form表单参数 和上传文件参数
 */
public class ParamNew {


    private List<FormParam> formParamList;

    private List<FileParam> fileParamList;

    public ParamNew(List<FormParam> formParamList) {
        this.formParamList = formParamList;
    }

    public ParamNew(List<FormParam> formParamList, List<FileParam> fileParamList) {
        this.formParamList = formParamList;
        this.fileParamList = fileParamList;
    }


    /**
     * 获取请求参数映射
     * @return
     */
    public Map<String,Object> getFieldMap(){
        Map<String,Object> fieldMap = new HashMap<String,Object>();

        if (CollectionUtils.isNotEmpty(formParamList)){
            for(FormParam formParam : formParamList){
                String fieldName = formParam.getFieldName();
                Object fieldValue = formParam.getFieldValue();
                if (fieldMap.containsKey(fieldName)){
                    fieldValue = fieldMap.get(fieldName)+ StringUtil.SEPERATOR+fieldValue;
                }
                fieldMap.put(fieldName,fieldValue);
            }

        }
        return fieldMap;
    }

    /**
     * 获取上传文件映射
     * @return
     */
    public Map<String,List<FileParam>> getFileMap(){

        HashMap<String, List<FileParam>> fileMap = new HashMap<>();

        if (CollectionUtils.isNotEmpty(fileParamList)){
            for(FileParam fileParam : fileParamList){
                String fieldName = fileParam.getFieldName();
                List<FileParam> fileParamList;
                if (fileMap.containsKey(fieldName)){
                    fileParamList = fileMap.get(fieldName);
                }else {
                    fileParamList = new ArrayList<>();
                }
                fileParamList.add(fileParam);
                fileMap.put(fieldName,fileParamList);
            }
        }

        return fileMap;
    }

    /**
     * 获取所有上传文件
     * @param fieldName
     * @return
     */
    public List<FileParam> getFileList(String fieldName){

        return getFileMap().get(fieldName);
    }


    /**
     * 获取单个上传文件
     * @param fieldName
     * @return
     */
    public FileParam getFile(String fieldName){
        Map<String, List<FileParam>> fileMap = getFileMap();
        if (fileMap.get(fieldName) != null && fileMap.get(fieldName).size() == 1){
            return fileMap.get(fieldName).get(0);
        }
        return null;
    }

}
